// pages/cart/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cart:[],
    check:false,
    totalPrice:0,
    totalnum:0
  },
  onShow(){
    const cart = wx.getStorageSync("cart") || [];
    let check=true;
    let totalPrice=0;
    let totalNum = 0;
    cart.forEach(v => {
      if(v.check){
        totalPrice += v.num*v.data.message.goods_price;
        totalNum += v.num
      }else{
        check=false
      }
    });
    check = cart.length!=0?check:false; 
    this.setData({
      cart,
      check,
      totalPrice,
      totalNum
    })
    
    
  },
  bindpay(){
    wx.navigateTo({
      url: '/pages/pay/index',
    })
  },
  bindcount(e){
    const {operation,id} =  e.currentTarget.dataset;
    let {cart} = this.data;
    const index = cart.findIndex(v=>v.data.message.goods_id === id);
    if(operation === 1){
      cart[index].num += 1;
    }else{
      if(cart[index].num === 1){
        wx.showModal({
          title: '提示',
          content: '确认要删除这个商品吗',
          success :(res)=> {
            if (res.confirm) {
              cart.splice(index,1)
              this.setcart(cart)
            } else if (res.cancel) {
              cart[index].num = 1
              this.setcart(cart)
            }
          }
        })
      }
      cart[index].num += -1;
    }
    this.setcart(cart)
  },
  bindcheckall(){
    let {cart,check} = this.data;
    check = !check;
    cart.forEach(v=>v.check = check)
    // this.setcart(cart)
    wx.setStorageSync('cart', cart)
    this.setData({
      cart,check
    })
  },
  bindcheck(e){
    const goods_id = e.currentTarget.dataset.id;
    let {cart} = this.data;
    console.log(cart)
    let index = cart.findIndex(v=>v.data.message.goods_id===goods_id);
    cart[index].check=!cart[index].check;
    this.setcart(cart)
  },
  setcart(cart){
    wx.setStorageSync('cart', cart)
    let check=true;
    let totalPrice=0;
    let totalNum = 0;
    cart.forEach(v => {
      if(v.check){
        totalPrice += v.num*v.data.message.goods_price;
        totalNum += v.num
      }else{
        check=false
      }
    });
    check = cart.length!=0?check:false; 
    this.setData({
      cart,
      check,
      totalPrice,
      totalNum
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
    // wx.chooseAddress({
    //   success: (result) => {
    //     console.log(result)
    //   },
    // })
    // wx.getSetting({
    //   success:(result)=>{
    //     console.log(result);
    //   },
    //   withSubscriptions: true,
    // })

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})